<!DOCTYPE html>
<html>
<head></head>
<body>

	
		<div class="modal-dialog modal-lg" th:fragment="maintainService">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">&times;</span><span class="sr-only">Cerrar</span>
					</button>
					<h4 class="modal-title" id="titleModalLabel">
						<span th:text="${#strings.isEmpty(servicevdnForm.id)}?${#messages.msg('title.newVDN')}:${#messages.msg('title.updateVDN')}" 
							th:remove="tag">Agregar</span></h4>
				</div>
				<div class="modal-body">
					<div class="row">

						<form id="formService" class="form-horizontal" role="form" th:object="${servicevdnForm}" method="post" 
							th:action="${#strings.isEmpty(servicevdnForm.id)}?@{/dashboard/servicevdn/save/new}:@{/dashboard/servicevdn/save/edit}">
							<input type="hidden" th:value="${servicevdnForm.id}" th:field="*{id}"/>
							<div class="col-xs-12 col-sm-5 col-md-4">
								<div class="form-group">
									<label for="input1" class="col-xs-5 col-sm-5 control-label"
										th:text="#{table.head.detail.service.validity}">Vigencia</label>
									<div class="col-xs-7 col-sm-7">
										<input type="hidden" th:field="*{status}" th:value="*{status}" />
										<div class="btn-group btn-toggle btnActive">
											<a href="javascript:void(0);" class="validity on btn btn-xs" th:classappend="*{#strings.defaultString(status,'enabled')=='enabled'} ? 'btn-primary active': 'btn-default'">ON</a> 
											<a href="javascript:void(0);" class="validity off btn btn-xs" th:classappend="*{#strings.defaultString(status,'')=='disabled'} ? 'btn-primary active': 'btn-default'">OFF</a>
										</div>
									</div>
								</div>
								<div class="form-group">
									<label for="input2" class="col-xs-5 col-sm-5 control-label"
										th:text="#{table.head.detail.service.vdn}">VDN</label>
									<div class="col-xs-7 col-sm-7" th:classappend="${#fields.hasErrors('vdn')} ? error">
										<select class="form-control" id="selectVdn" th:field="*{vdn}">
											<option value="0" selected="selected">Seleccione</option>
											<option th:each="vdn : ${vdns}" 
												th:text="${vdn.value}" th:value="${{vdn.value}}"
												>[option]</option>
										</select>
										<span class="help-inline" th:errors="*{vdn}">[error]</span>
									</div>
								</div>
								<div class="form-group">
									<label for="input2" class="col-xs-5 col-sm-5 control-label"
										th:text="#{table.head.detail.service.vdnout}">VDN
										outsite</label>
									<div class="col-xs-7 col-sm-7" th:classappend="${#fields.hasErrors('vdnOutHour')} ? error">
										<select class="form-control" id="selectVdnOutHour" th:field="*{vdnOutHour}">
											<option value="0" selected="selected">Seleccione</option>
											<option th:each="vdn : ${vdns}" 
											th:text="${vdn.value}" th:value="${{vdn.value}}"
											>[option]</option>
										</select>
										<span class="help-inline" th:errors="*{vdnOutHour}">[error]</span>
									</div>
								</div>
								<div class="form-group">
									<label for="inputRate" class="col-xs-5 col-sm-5 control-label" 
										th:text="#{table.head.detail.service.weighing}">Ponderacion</label>
									<div class="col-xs-7 col-sm-7" th:classappend="${#fields.hasErrors('rate')} ? error">
										<input type="text" class="form-control inputNumber" id="inputRate" th:value="*{rate}"
											placeholder="Ponderacion" th:field="*{rate}" maxlength="2"/>
											<span class="help-inline" th:errors="*{rate}">[error]</span>
									</div>
								</div>
								<div class="form-group">
									<label for="audioNameServHour" class="col-xs-5 col-sm-5 control-label" 
										th:text="#{table.head.detail.service.audioNameServ}">AudioNameServ</label>
									<div class="col-xs-7 col-sm-7" th:classappend="${#fields.hasErrors('audioNameServHours')} ? error">
										<select class="form-control" th:field="*{audioNameServHours}">
											<option value="0" selected="selected">Seleccione</option>
											<option th:each="audio : ${audioServiceHours}" 
												th:text="${audio.name}" th:value="${{audio.name}}"
												>[option]</option>
										</select>
										<span class="help-inline" th:errors="*{audioNameServHours}">[error]</span>
									</div>
								</div>
								<div class="form-group">
									<label for="audioNameOutServHour" class="col-xs-5 col-sm-5 control-label" 
										th:text="#{table.head.detail.service.audioNameOutServ}">AudioNameOutServ</label>
									<div class="col-xs-7 col-sm-7" th:classappend="${#fields.hasErrors('audioNameOutServHours')} ? error">
										<select class="form-control" th:field="*{audioNameOutServHours}">
											<option value="0" selected="selected">Seleccione</option>
											<option th:each="audio : ${audioOutServiceHours}" 
												th:text="${audio.name}" th:value="${{audio.name}}"
												>[option]</option>
										</select>
										<span class="help-inline" th:errors="*{audioNameOutServHours}">[error]</span>
									</div>
								</div>
							</div>

							<div class="col-xs-12 col-sm-7 col-md-8 inputHour" th:with="lista=*{#strings.listSplit(#strings.defaultString(serviceHour,''),'|')}, ordered=${#lists.sort(lista)}">
							
								<input type="hidden" th:value="${ordered}" th:field="*{serviceHour}"/>
					      			 
								<div class="form-group oneDayHour" th:each="one, row : ${#numbers.sequence(1,7,1)}">
									<div class="col-xs-2 col-sm-3 text-right">
						      			<label for="" th:for="|id${row.count}|"
						      				th:text="${#messages.msg(#strings.append('long.day',one))}">Lunes</label>
									</div>
					      			<div class="col-xs-10 col-sm-9">
					      				<input type="hidden" th:id="|indexDay${row.count}|" class="indexDay" th:value="${row.count}" />
					      				<div class="col-xs-4 col-sm-4 btn-group btn-toggle">
									    	<a href="javascript:void(0)" class="day on btn btn-xs " th:classappend="*{serviceHour==null}?'btn-primary active':'btn-default'">ON</a>
									    	<a href="javascript:void(0)" class="day off btn btn-xs " th:classappend="*{serviceHour==null}?'btn-default':'btn-primary active'">OFF</a>
									    </div>
									    <div class="col-xs-8 col-sm-8">
									    	<fieldset>
										    	<div class="col-xs-6 col-sm-6">
											    	<input type="text" class="form-control input-sm inputNumber" id="number01" placeholder="start" 
											    		th:id="|idStar${row.count}|" maxlength="2"/>
											    </div>
											    <div class="col-xs-6 col-sm-6">
											    	<input type="text" class="form-control input-sm inputNumber" id="number02" placeholder="final" 
											    		th:id="|idEnd${row.count}|" maxlength="2"/>
											    </div>
									    	</fieldset>
									    </div>
						      			
								    </div>
					      		</div>
					      		
								
							</div>
							<input type="hidden" id="modalProcess" name="modalProcess" value=""/>
						</form>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" id="ok" class="btn btn-primary">Aceptar</button>
					<button type="button" id="cancel" class="cancel btn btn-default" data-dismiss="modal">Cancelar</button>
				</div>
				<input type="hidden" id="excludevdn" name="excludevdn" th:value="${excludevdn}"/>
				<input type="hidden" id="excludevdnhour" name="excludevdnhour" th:value="${excludevdnhour}"/>
			</div>
			
			<script type="text/javascript" th:inline="javascript">
			
			$(function(){
				
				$("input.inputNumber").focusout(function(event) {
					var number = $(this).val();
					if(!validNumberto24(number)){
						event.preventDefault();
						alert("No debe ser mayor a 24");
						document.getElementById(''+$(this).attr("id")+'').select();
						document.getElementById(''+$(this).attr("id")+'').focus();
						//$(this).select();
						//$(this).focus().select();
					}
				});
				var inputStatus = $("#status");
				if($(".btnActive").find('.active').hasClass("on")){
					$(inputStatus).val("enabled");
					//$("#ok").attr("disabled",false);
					$("#formService select").attr("disabled",false);
					$("#formService input").prop("disabled", false);
					$("a.day").removeClass("disabled");
				}else{
					$(inputStatus).val("disabled");
					//$("#ok, select").attr("disabled",true);
					$("#formService select").attr("disabled",true);
					$("#formService input").prop("disabled", true);
					$("a.day").addClass("disabled");
				}
				
				var serviceHour = $("#serviceHour").val();
	            var lines =  serviceHour.split("|");
	            var objetoClass = $(".indexDay");
	            if(serviceHour.length > 0){
	            	var fieldSet = $(".inputHour").find('fieldset');
	            	$(fieldSet).find("input").prop('disabled',true);
	            	//$(fieldSet).attr('disabled',true);
	            }
	            $.each(lines, function(key, line){
	                var firstNumber = line.charAt(0);
	                $(objetoClass).each(function(index, val) {
	                    var localValue = $(this).val();
	                    if(parseInt(localValue,10) == parseInt(firstNumber,10)){
	                        var startValue = line.substring(1,line.length-2);
	                        var endValue = line.substring(line.length-2, line.length);
	                        $(this).parent().find('.day').each(function(index, el) {
	                            if(index==0){
	                                $(el).removeClass('btn-default').addClass('btn-primary active');
	                            }else{
	                                $(el).removeClass('btn-primary active').addClass('btn-default');
	                            }
	                        });
	                        $(this).parent().find('input.inputNumber').each(function(index, el) {
	                            if(index==0)
	                                $(el).val(parseInt(startValue,10));
	                            else
	                                $(el).val(parseInt(endValue,10));
	                        });
	                        var fieldSet = $(this).parent().find('fieldset');
	    	            	$(fieldSet).find("input").prop('disabled',false);
	    	            	//$(fieldSet).attr('disabled',false);
	                    }
	                });
	            });
					
				$(".validity").click(function(){
					var parent = $(this).parent();
					parent.find('.btn').removeClass('active');
					parent.find('.btn').removeClass('btn-default');
					parent.find('.btn').removeClass('btn-primary');
					if($(this).hasClass("on")){
						$(inputStatus).val("enabled");
						parent.find('.on').addClass('btn-primary');
						parent.find('.off').addClass('btn-default');
						parent.find('.on').addClass('active');
	                	
	                    $("#formService select").attr("disabled",false);
	                    $("#formService input").prop("disabled", false);
	                    $("a.day").removeClass("disabled");
						$.each($("a.day.off.active"), function(index, value){
							var index = $(this).parent().parent().find("input.indexDay").val();
							$("#idStar"+index).prop("disabled", true);
							$("#idEnd"+index).prop("disabled", true);
						}) ;
						
					}else{
						$(inputStatus).val("disabled");
						parent.find('.on').addClass('btn-default');
						parent.find('.off').addClass('btn-primary');
						parent.find('.off').addClass('active');
	                	
	                    $("#formService select").attr("disabled",true);
	                    $("#formService input").prop("disabled", true);
	                    $("a.day").addClass("disabled");
					}
				});
				
				$("a.day").click(function(){
	                var parent = $(this).parent().parent();
	                $(this).parent().find('.btn').removeClass('active');
	                $(this).parent().find('.btn').removeClass('btn-default');
                	$(this).parent().find('.btn').removeClass('btn-primary');
	                if($(this).hasClass('on')){
	                	$(this).parent().find('.on').addClass('btn-primary');
	                	$(this).parent().find('.off').addClass('btn-default');
	                	$(this).parent().find('.on').addClass('active');
	                    $(parent).find("input").attr("disabled",false);
	                }else{
	                	$(this).parent().find('.on').addClass('btn-default');
	                	$(this).parent().find('.off').addClass('btn-primary');
	                	$(this).parent().find('.off').addClass('active');
	                    $(parent).find("input").attr("disabled",true);
	                }
	            });
				
				// <![CDATA[
				$("#formService input.inputNumber").keydown(function(event) {
					if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || 
							event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
						// let it happen, don't do anything
					}else if (event.keyCode < 48 || event.keyCode > 57 ) {
						event.preventDefault();
					}
				});
				// ]]>
				$('#formService input').bind("cut copy paste",function(e) {
			          e.preventDefault();
			    });
				
				// <![CDATA[
				$("#ok").click(function(event){
					event.preventDefault();
					var validId = "";
					var urlAction = "";
					var inputStatus = $("#status").val();
					if(inputStatus=="disabled"){
						urlAction = /*[[@{/dashboard/servicevdn/save/edit/vality/}]]*/ 
						//console.log(urlAction);
	                    validId = $("#formService").find("#id").val();
	                    if(validId==""){
	                    	alert("No puede registrar una vdn desabilitada");
	                    	return;
	                    }else
	                    	$("#modalProcess").val("update");
	                	var datastring = "modalProcess="+$("#modalProcess").val()+"&valityUpdate="+inputStatus+"&idService="+validId;
	                	//console.log(datastring);
	                    $.ajax( {
	                        type: "POST",
	                        url: urlAction,
	                        data: datastring,
	                        success: function( response ) {
	                          $("#ModalEditFormVDN").modal('hide');
	                          $('body').removeClass('modal-open');
	                          $('.modal-backdrop').remove();
	                          $("#detailService").html(response);
	                        },
	                        error: function(error){
	                        	if(error.status == "500")
	                        		$("body").html(error.responseText);
	                         }
	                      });
					}else{
		                var inputConcat = "";
		                var objClass = $(".day", ".oneDayHour");
		                var validNumber = true; 
		                var validHour = false;
		                if(!validateFormulario(validHour)){
		                	return;
		                }
		                validHour = true;
		                var lstvdnshour = $("#lstvdnhour").val();
		                var seleVdnOutHour = $("#selectVdnOutHour").val();
		                $(objClass).each(function(){
		                    if($(this).hasClass("on") && $(this).hasClass("active")){
		                    	var parents = $(this).parents(".oneDayHour");
		                        var indexDay = $(parents).find(".indexDay").val();
		                        var fieldset = $(parents).find("fieldset");
		                        if($(fieldset).prop('disabled') == false){
		                            var inputLocalIni = '';
		                            if(inputConcat.length > 0)
		                                inputConcat += '|';
	
		                            $(fieldset).find("input").each(function(){
		                                var localValue = eval2DigitsNumber($(this).val());
		                                if(parseInt(localValue,10) < 0){
		                                    alert("No puede ser valor negativo.");
		                                    $(this).focus();
		                                    validNumber = false;
		                                    return;
		                                }
		                                
		                                if(!validNumberto24(parseInt(localValue,10))){
		                                	alert("No debe ser mayor a 24");
		                                	$(this).select();
		                                	$(this).focus();
		                                    validNumber = false;
		                                    return;
		                                }
		                                
		                                if(inputLocalIni == '')
		                                    inputLocalIni = localValue;
		                                else if(parseInt(localValue,10) > parseInt(inputLocalIni,10)){
		                                	var intIni = parseInt(inputLocalIni,10);
		                                	var intFin = parseInt(localValue,10);
		                                	if((intFin - intIni) < 24){
		                                		if(seleVdnOutHour=="0"){
		                        					alert("Debe escoger una vdn out hour.");
		                        					$("#selectVdnOutHour").focus();
		                        					validNumber = false;
		                        					return;
		                        				}
		                                	}
		                                	inputConcat += indexDay + inputLocalIni + localValue;
		                                }else{
		                                    alert("No debe de ser: Inicio "+inputLocalIni+"   Fin "+localValue);
		                                    validNumber = false;
		                                    return;
		                                }
		                            });
		                        }
		                    }
		                    return validNumber;
		                });
		                if(validNumber){
		                    $("#serviceHour").val(inputConcat);
		                    if(validateFormulario(validHour)){
		                    	var vdncurrent = $("#selectVdn").val();
		                    	var lstvdns = $("#lstvdn").val();
		                    	/*if(lstvdnshour!="" && seleVdnOutHour!="0" && validateVdnstorage(lstvdnshour, seleVdnOutHour, $("#excludevdnhour").val())){
		                    		alert("Ya existe la vdn out hour seleccionada.\nSeleccione otra..");
		                    		$("#selectVdnOutHour").focus();
		                    		validNumber = false;
		                    		return;
		                    	}*/
		                    	if(validateVdnstorage(lstvdns, vdncurrent, $("#excludevdn").val())){
		                    		alert("Ya existe la vdn seleccionada.\nSeleccione otra..");
		                    		$("#selectVdn").focus();
		                    		return;
		                    	}else{
				                    urlAction = $("#formService").attr("action");
				                    var validId = $("#formService").find("#id").val();
				                    if(validId=="")
				                    	$("#modalProcess").val("insert");
				                    else
				                    	$("#modalProcess").val("update");
				                	var datastring = $("#formService").serialize();
				                    $.ajax( {
				                        type: "POST",
				                        url: urlAction,
				                        data: datastring,
				                        success: function( response ) {
				                          $("#ModalEditFormVDN").modal('hide');
				                          $('body').removeClass('modal-open');
				                          $('.modal-backdrop').remove();
				                          $("#detailService").html(response);
				                        },
				                        error: function(error){
				                        	if(error.status == "500")
				                        		$("body").html(error.responseText);
				                         }
				                      });
		                    	}
		                    	
		                    }
		                }
					}
	                    
	            });
				// ]]>
				
			});
			
			function validateFormulario(validHour){
				var form = $("#formService");
				var seleVdn = $(form).find("#selectVdn").val();
				if(seleVdn=="0"){
					alert("Debe escoger una vdn.");
					$("#selectVdn").focus();
					return false;
				}
				var rate = $(form).find("#inputRate").val();
				if(parseInt(rate,10) == 0 ){
					alert("Debe introducir una poderacion.");
					$("#inputRate").select();
					$("#inputRate").focus();
					return false;
				}
				if(validHour){
					var serviceHour = $(form).find("#serviceHour").val();
					if(serviceHour == ""){
						alert("Debe introducir por lo menos un horario.");
						return false;
					}
				}
				return true;
			}
			
			// <![CDATA[
			function validateVdnstorage(listvdns, currentvdn, excludevdn){
				var arrayVdn = listvdns.split(",");
				var flagVdn=false;
				if(excludevdn == "")
					excludevdn=="0";
				$.each(arrayVdn, function(index, value){
					if(excludevdn!=currentvdn && value == currentvdn){
						//console.log('Repeat vdn in '+index+') '+value);
						flagVdn = true;
					}
				});
				return flagVdn;
			}
			// ]]>
			
		</script>
		</div>
		
		
	
</body>
</html>